package com.paddyi.service.impl;

import com.paddyi.enums.OrderStatusEnum;
import com.paddyi.feignService.AccountService;
import com.paddyi.feignService.StockService;
import com.paddyi.mapper.ProductMapper;
import com.paddyi.model.Account;
import com.paddyi.model.Product;
import com.paddyi.model.Stock;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.paddyi.model.PaddyOrder;
import com.paddyi.mapper.PaddyOrderMapper;
import com.paddyi.service.IPaddyOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  (PaddyOrder)
 * @author paddy
 * @since  2019-08-09 15:56:40
 */
@Service
public class PaddyOrderServiceImpl extends ServiceImpl<PaddyOrderMapper, PaddyOrder> implements IPaddyOrderService {


    @Autowired
    PaddyOrderMapper paddyOrderMapper;
    @Autowired
    StockService stockService;
    @Autowired
    AccountService accountService;
    @Autowired
    ProductMapper productMapper;

    @Override
    @GlobalTransactional
    public boolean makePayOrder(PaddyOrder order) {
//        order.setNumber(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        order.setCount(1);
        order.setCreateTime(new Date());
        order.setProductId(1L);
        order.setStatus(OrderStatusEnum.NOT_PAY.getCode());
        order.setTotalAmount(new BigDecimal(1));
        order.setUserId(1L);
        //减库存
        Stock stock = new Stock();
        stock.setLockStock(order.getCount());
        stock.setProductId(order.getProductId());
        stockService.place(stock);

        //扣钱
        Account account = new Account();
        account.setFreezeAmount(order.getTotalAmount());
        account.setUserId(order.getUserId());
        accountService.pay(account);

        if(order.getNumber().equals("1")){
            throw new RuntimeException();
        }
        paddyOrderMapper.insert(order);
        return true;
    }

    @Override
    @Transactional
    public boolean transactionTest(){
        PaddyOrder paddyOrder = paddyOrderMapper.selectById(48);
        paddyOrder.setStatus(1);
        paddyOrderMapper.updateById(paddyOrder);

        int i = productMapper.pay();
        if(i!=1){
            throw new RuntimeException();
        }
        return true;
    }

    public boolean confirm(PaddyOrder order) {
        order.setStatus(OrderStatusEnum.PAY_SUCCESS.getCode());
        paddyOrderMapper.updateById(order);
        return Boolean.TRUE;
    }

    public boolean cancel(PaddyOrder order) {
        order.setStatus(OrderStatusEnum.PAY_FAIL.getCode());
        paddyOrderMapper.updateById(order);
        return Boolean.TRUE;
    }
}
